/*
 * @Description: token 令牌
 * @Author: lgt
 * @Date: 2021-06-27 20:23:57
 * @LastEditTime: 2021-07-10 08:59:40
 * @LastEditors: xxx
 */
 const bcrypt = require('bcryptjs'); //密码加密包
const Router = require('koa-router');
const {success} = require("../../lib/helper")
const router = new Router(
    {
        prefix:'/v1/token'
    }
);

//导入校验器
const {RegisterValidator} = require("../../validators/validator")
const { TokenValidator, NotEmptyValidator } = require("../../validators/validator")
//导入 model
const { User } = require("../../models/user")

//导入meiju
const { LoginType } = require("../../lib/enum")

// 导入生成token
const {generateToken} = require('../../../core/util')

const {Auth} = require('../../../middlewares/auth')
const {WXManager} = require('../../services/wx') 



router.post('/',async(ctx,next)=>{
    //思维方式  接收参数、参数校验
    const v =await new TokenValidator().validate(ctx); // 校验中有异步操作
    let token;
    //判断不同参数值，编写不同的逻辑 
    // USER_MINI_PROGRAM,USER_EMAIL,USER_MOBILE,ADMIN_EMAIL
   switch (v.get('body.type')) {
        // email登录
        case LoginType.USER_EMAIL:
            token = await emailLogin(v.get('body.account'), v.get('body.secret'))
            break;

        // 小程序登录
        case LoginType.USER_MINI_PROGRAM:
            token = await WXManager.codeToToken(v.get('body.account'))
            break;

        // 管理员登录
        case LoginType.ADMIN_EMAIL:
            break;

        default:
            throw new global.errs.ParameterException('没有相应的处理函数')
    }


    ctx.body = {
        token
    }

})


router.post('/verify', async (ctx) => {
    const v = await new NotEmptyValidator().validate(ctx)
    const result = Auth.verifyToken(v.get('body.token'))

    ctx.body = {
        isValid: result
    }
})

async function emailLogin(account, secret) {
    const user = await User.verifyEmailPassword(account, secret)
    // 发布令牌
    return generateToken(user.id, Auth.AUSE)
}


module.exports = router;